#! encoding=utf-8

import requests
from common import HOST
import traceback
import urllib


def add(tag):
    url = HOST + '/user'
    print "POST /user 创建用户 ..."
    ret = None
    try:
        ret = requests.session().post(url, {'tag': tag}).content
    except:
        print traceback.format_exc()
    finally:
        print ret


def get(skip, limit):
    url = HOST + '/user'
    print "GET /user 获取所有用户 ..."
    ret = None
    try:
        ret = requests.session().get(url + '?skip=' + skip + '&limit=' + limit).content
    except:
        print traceback.format_exc()
    finally:
        print ret


def delete(user_id):
    url = HOST + '/user/' + user_id
    print "Delete /user/{user_id} 删除某个用户 ..."
    try:
        requests.session().delete(url)
    except:
        print traceback.format_exc()


def getUser(user_id):
    url = HOST + '/user/' + user_id
    print "GET /user/{user_id} 获取单个用户 ..."
    ret = None
    try:
        ret = requests.session().get(url).content
    except:
        print traceback.format_exc()
    finally:
        print ret


def update(user_id, tag):
    url = HOST + '/user/' + user_id
    print "PUT /user/{user_id} 修改某个用户 ..."
    ret = None
    try:
        ret = requests.session().put(url, {'tag': tag}).content
    except:
        print traceback.format_exc()
    finally:
        print ret


def image(user_id, quality_threshold, image):
    url = HOST + '/user/' + user_id + '/image'
    print "POST /user/{user_id}/image 向用户加入图片 ..."
    ret = None
    try:
        ret = requests.session().post(url, {'quality_threshold': quality_threshold}, files={'image': ('filename.jpg', open(image, 'rb'))}).content
    except:
        print traceback.format_exc()
    finally:
        print ret


def deleteImage(user_id, image_id):
    url = HOST + '/user/' + user_id + '/image/' + image_id
    print "DELETE /user/{user_id}/image/{image_id} 删除用户的图片 ..."
    try:
        requests.session().delete(url)
    except:
        print traceback.format_exc()


def query(query, skip, limit):
    url = HOST + '/user_query/'
    print "GET /user_query 查询用户 ..."
    ret = None
    try:
        ret = requests.session().get(url + '?query=' + query + '&skip=' + skip + '&limit=' + limit).content
    except:
        print traceback.format_exc()
    finally:
        print ret


def getImage(image_id):
    url = HOST + '/image/' + image_id
    print "GET /image/{image_id} 获得图片"
    try:
        urllib.urlretrieve(url, image_id + '.jpg')
    except:
        print traceback.format_exc()

